from django.shortcuts import render
from django.http import HttpResponse, JsonResponse

from .. import models
from django.core.urlresolvers import reverse

# 商品分类  添加
def catesadd(request):
    if request.method == 'GET':
        # 获取所有的商品分类
        data = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
        # 分配数据
        context = {'cateslist': data}
        # 加载模板
        return render(request, 'myadmin/cates/add.html', context)
    elif request.method == 'POST':
        # try:
            # 执行添加
            ob = models.Cates()
            ob.name = request.POST.get('name')
            ob.pid = request.POST.get('pid')
            # 判断是否为顶级分类
            if ob.pid == '0':
                ob.path = '0,'
            else:
                # 获取当前所选的分类的path
                fob = models.Cates.objects.get(id=ob.pid)
                ob.path = fob.path+ob.pid+','
            ob.save()
            return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_cates_index')+'"</script>')
        # except:
            return HttpResponse('<script>alert("添加失败");location.href="'+reverse('myadmin_cates_add')+'"</script>')

# 商品分类 列表
def catesindex(request):
    # 获取所有的商品分类
    # data = modefs.Cates.objects.all()
    # select *,concat(path,id) as paths from myadmin_cates order by paths;

    data = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')

    # 数据分页
    from django.core.paginator import Paginator
    # 实例化分页类
    paginator = Paginator(data,10)

    # 获取当前页码
    p = int(request.GET.get('p',1))

    # 获取分页数据对象[{id:1},{id:2}]  [{id:3},{id:4}]
    cateslist = paginator.page(p)

    # 分配数据
    context = {'cateslist':cateslist}
    # 加载模板
    return render(request, 'myadmin/cates/index.html',context)

# 分类 删除
def catesdel(request):
    # 分类id
    cid = request.GET.get('cid')

    # 判断当前类下是否还有子类
    num = models.Cates.objects.filter(pid=cid).count()
    if num:
        # 有子类,不能删除
        return JsonResponse({'error':1,'msg':'当前类下有子类,不能删除'})

    # 再确认当前类下是否有商品发布
    # 获取分类对象
    ob = models.Cates.objects.get(id=cid)
    ob.delete()
    return JsonResponse({'error':0,'msg':'删除成功'})

# 分类的修改
def catesedit(request):
    try:
        # 根据cid获取分类对象
        ob = models.Cates.objects.get(id=request.GET.get('cid'))
        ob.name = request.GET.get('name')
        ob.save()
        return JsonResponse({'error':0,'msg':'更新成功'})
    except:
        return JsonResponse({'error':1, 'msg':'更新失败'})